package com.szqhyxj.youxiangju.biz.merchantHome;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.szqhyxj.youxiangju.BaseActivity;
import com.szqhyxj.youxiangju.R;
import com.szqhyxj.youxiangju.biz.InstallUtil;
import com.szqhyxj.youxiangju.biz.core.App;
import com.szqhyxj.youxiangju.biz.core.SharedPreferencesUtil;
import com.szqhyxj.youxiangju.biz.entrace.EntranceManager;
import com.szqhyxj.youxiangju.biz.equipmentActivation.equipmentCardslot.EquipmentCardSlotActivity;
import com.szqhyxj.youxiangju.biz.login.LoginActivity;
import com.szqhyxj.youxiangju.biz.merchantHome.home.MerchantHomeFragment;
import com.szqhyxj.youxiangju.biz.merchantHome.my.MyFragment;
import com.szqhyxj.youxiangju.biz.merchantHome.net.NetPopView;
import com.szqhyxj.youxiangju.biz.merchantHome.notice.NoticeModel;
import com.szqhyxj.youxiangju.biz.merchantHome.notice.NoticePopView;
import com.szqhyxj.youxiangju.biz.merchantHome.plan.PlansFragment;
import com.szqhyxj.youxiangju.biz.merchantHome.shop.ShopFragment;
import com.szqhyxj.youxiangju.biz.realNameAuth.idcard.IDCardAuthActivity;
import com.szqhyxj.youxiangju.biz.update.UpdateContract;
import com.szqhyxj.youxiangju.biz.update.UpdatePresenter;
import com.szqhyxj.youxiangju.biz.update.bean.UpdateInfo;
import com.szqhyxj.youxiangju.biz.web.WebActivity;
import com.szqhyxj.youxiangju.sys.components.view.dialog.DownloadDialog;
import com.szqhyxj.youxiangju.sys.components.view.popview.OutlinePopView;
import com.szqhyxj.youxiangju.sys.components.view.popview.RealNamePopView;
import com.szqhyxj.youxiangju.sys.components.view.popview.UpdatePopView;
import com.szqhyxj.youxiangju.sys.util.ApkUtil;
import com.szqhyxj.youxiangju.sys.util.NetWorkUtils;
import com.szqhyxj.youxiangju.sys.util.ToastUtils;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by leung on 2018/10/30.
 */

public class MerchantContainerActivity extends BaseActivity implements
        UpdateContract.View,
        MerchantContainerContract.View,
        UpdatePopView.onClickImmediatelyGo,
        NetPopView.RetryClickListener {


    @BindView(R.id.home_icon)
    ImageView homeIcon;
    @BindView(R.id.home_title)
    TextView homeTitle;
    @BindView(R.id.home)
    LinearLayout home;
    @BindView(R.id.shop_icon)
    ImageView shopIcon;
    @BindView(R.id.shop_title)
    TextView shopTitle;
    @BindView(R.id.shop)
    LinearLayout shop;
    @BindView(R.id.plan_icon)
    ImageView planIcon;
    @BindView(R.id.plan_title)
    TextView planTitle;
    @BindView(R.id.plan)
    LinearLayout plan;
    @BindView(R.id.my_icon)
    ImageView myIcon;
    @BindView(R.id.my_title)
    TextView myTitle;
    @BindView(R.id.my)
    LinearLayout my;
    @BindColor(R.color.gray)
    int colorNormal;
    @BindColor(R.color.invitationColor)
    int colorSelected;

    private static final String TAG = MerchantContainerActivity.class.getSimpleName();
    @BindView(R.id.container)
    CustomViewPager container;
    @BindView(R.id.navigator)
    LinearLayout navigator;

    private static final String TYPEPAGE = "typePage";
    private static final String ISREFRESH = "isRefresh";
    @BindView(R.id.next)
    TextView next;

    @BindView(R.id.know)
    TextView know;
    @BindView(R.id.guider01)
    LinearLayout guider01;
    @BindView(R.id.guider02)
    LinearLayout guider02;
    @BindView(R.id.guider03)
    LinearLayout guider03;
    @BindView(R.id.guider04)
    LinearLayout guider04;
    @BindView(R.id.guider05)
    LinearLayout guider05;
    private MerchantContainerContract.Presenter presenter;
    private UpdateContract.Presenter updatePresenter;
    private DownloadDialog downloadDialog;
    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    public static int UNKNOWN_CODE = 2018;
    private InstallUtil mInstallUtil;

    public static void start(Activity activity) {
        Intent intent = new Intent();
        intent.setClass(activity, MerchantContainerActivity.class);
        activity.startActivity(intent);

    }

    public static void start(Activity activity, boolean isRefresh) {
        Intent intent = new Intent();
        intent.setClass(activity, MerchantContainerActivity.class);
        intent.putExtra(ISREFRESH, isRefresh);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, boolean isRefresh, int type) {
        Intent intent = new Intent();
        intent.setClass(activity, MerchantContainerActivity.class);
        intent.putExtra(ISREFRESH, isRefresh);
        intent.putExtra(TYPEPAGE, type);
        activity.startActivity(intent);


    }

    private List<Fragment> fragments = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchant_container);
        ButterKnife.bind(this);
        presenter = new MerchantContainerPresenter(this);
        presenter.init();
        // 与后台绑定推送cid
        presenter.setClientid(PushManager.getInstance().getClientid(this));
        updatePresenter = new UpdatePresenter(this);
        updatePresenter.checkUpdate(this);
        EntranceManager.INSTANCE.setToMerchant();
        presenter.setNotice();
        int net = NetWorkUtils.getAPNType(this);
        initNetView(net, this);
        Boolean d = SharedPreferencesUtil.getHomeShow();
        Log.e("aaa", d + "");
        if (SharedPreferencesUtil.getHomeShow()) {
            guider01.setVisibility(View.GONE);
            guider02.setVisibility(View.GONE);
            container.setVisibility(View.VISIBLE);
            navigator.setVisibility(View.VISIBLE);
        } else {
            guider01.setVisibility(View.VISIBLE);
            guider02.setVisibility(View.GONE);
            container.setVisibility(View.GONE);
            navigator.setVisibility(View.GONE);
        }
        addPermission();
    }

    private void addPermission() {
        AndPermission.with(this)
                .runtime()
                .permission(permissions)
                .onGranted(permissions -> {
                    // Storage permission are allowed.
                })
                .onDenied(permissions -> {
                    // Storage permission are not allowed.
                    ToastUtils.showTost(getApplicationContext(), "沒有权限，请到设置页面授予权限.");
                })
                .start();
    }

    /**
     * 网络判断
     *
     * @param net
     */
    NetPopView netPopView;

    private void initNetView(int net, Context context) {

        if (net == 0) {
            Toast.makeText(this, "请连接网络", Toast.LENGTH_LONG).show();
            netPopView = new NetPopView(this, this);
            netPopView.show();

           /* AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setTitle("温馨提示：")
                    .setMessage("请连接网络，确定进行刷新");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int net2 = NetWorkUtils.getAPNType(context);
                    if (net2 == 0) {
                        Toast.makeText(context, "请连接网络", Toast.LENGTH_LONG).show();
                        builder.show();
                    } else {
                        presenter.init();
                    }
                }
            }).show();*/

        } else {
            //    Toast.makeText(this, "网络已连接", Toast.LENGTH_LONG).show();
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //是否刷新首页数据
        boolean isRefresh = intent.getBooleanExtra(ISREFRESH, true);

        if (isRefresh) {
            presenter.init();
            //与后台绑定推送cid
            presenter.setClientid(PushManager.getInstance().getClientid(this));
        } else {

        }

        if (intent.getIntExtra(TYPEPAGE, -1) == MerchantType.HOME.getCode()) {
            presenter.setHome();
        }

        if (intent.getIntExtra(TYPEPAGE, 0) == MerchantType.SHOP.getCode()) {
            presenter.setShop();
        }

        if (intent.getIntExtra(TYPEPAGE, 0) == MerchantType.PLAN.getCode()) {
            presenter.setPlan();
        }

        if (intent.getIntExtra(TYPEPAGE, 0) == MerchantType.MY.getCode()) {
            presenter.setMy();
        }
    }

    @OnClick({R.id.home, R.id.shop, R.id.plan, R.id.my, R.id.next, R.id.know, R.id.next01, R.id.next02, R.id.know01})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.home:
                presenter.setHome();
                break;
            case R.id.shop:
                presenter.setShop();
                break;
            case R.id.plan:
                presenter.setPlan();
                break;
            case R.id.my:
                presenter.setMy();
                break;
            case R.id.next:
                guider01.setVisibility(View.GONE);
                guider02.setVisibility(View.VISIBLE);
                container.setVisibility(View.GONE);
                navigator.setVisibility(View.GONE);
                break;
            case R.id.know:
                guider01.setVisibility(View.GONE);
                guider02.setVisibility(View.GONE);
                container.setVisibility(View.VISIBLE);
                navigator.setVisibility(View.VISIBLE);
                SharedPreferencesUtil.setHomeshow(true);
                break;
            case R.id.next01:
                guider03.setVisibility(View.GONE);
                guider04.setVisibility(View.VISIBLE);
                guider05.setVisibility(View.GONE);
                container.setVisibility(View.GONE);
                navigator.setVisibility(View.GONE);
                break;
            case R.id.next02:
                guider03.setVisibility(View.GONE);
                guider04.setVisibility(View.GONE);
                guider05.setVisibility(View.VISIBLE);
                container.setVisibility(View.GONE);
                navigator.setVisibility(View.GONE);
                break;

            case R.id.know01:
                guider03.setVisibility(View.GONE);
                guider04.setVisibility(View.GONE);
                guider05.setVisibility(View.GONE);
                container.setVisibility(View.VISIBLE);
                navigator.setVisibility(View.VISIBLE);
                SharedPreferencesUtil.setMyshow(true);
                container.setCurrentItem(3, false);
                reset();
                myIcon.setImageResource(R.mipmap.wode);
                myTitle.setTextColor(colorSelected);
                break;
        }
    }

    private void reset() {
        homeIcon.setImageResource(R.mipmap.shouye_01);
        shopIcon.setImageResource(R.mipmap.gouji_01);
        planIcon.setImageResource(R.mipmap.yeji_02);
        myIcon.setImageResource(R.mipmap.wode_01);
        homeTitle.setTextColor(colorNormal);
        shopTitle.setTextColor(colorNormal);
        planTitle.setTextColor(colorNormal);
        myTitle.setTextColor(colorNormal);
    }

    @Override
    public void showAll() {
        fragments.clear();
        MerchantHomeFragment homeFragment = MerchantHomeFragment.newInstance();
        fragments.add(homeFragment);
        fragments.add(ShopFragment.newInstance());
        fragments.add(PlansFragment.newInstance());
        MyFragment myFragment = MyFragment.newInstance();
        myFragment.setGoShopListener(new MyFragment.GoShopListener() {
            @Override
            public void goShop() {
                MerchantContainerActivity.this.presenter.setShop();
            }
        });

        homeFragment.setGoShopListener(new MerchantHomeFragment.GoShopListener() {
            @Override
            public void goShop() {
                MerchantContainerActivity.this.presenter.setShop();
            }
        });
        fragments.add(myFragment);
        container.setAdapter(new MerchantFragmentsContainer(getSupportFragmentManager(), fragments));
        container.setOffscreenPageLimit(4);
    }

    @Override
    public void showHome() {
        container.setCurrentItem(0, false);
        reset();
        homeIcon.setImageResource(R.mipmap.shouye);
        homeTitle.setTextColor(colorSelected);
    }

    @Override
    public void showShop() {
        container.setCurrentItem(1, false);
        reset();
        shopIcon.setImageResource(R.mipmap.gouji);
        shopTitle.setTextColor(colorSelected);
    }

    @Override
    public void showPlan() {
        container.setCurrentItem(2, false);
        reset();
        planIcon.setImageResource(R.mipmap.yeji);
        planTitle.setTextColor(colorSelected);
    }

    @Override
    public void showMy() {
        if (SharedPreferencesUtil.getMyShow()) {
            container.setCurrentItem(3, false);
            reset();
            myIcon.setImageResource(R.mipmap.wode);
            myTitle.setTextColor(colorSelected);
        } else {
            container.setVisibility(View.GONE);
            navigator.setVisibility(View.GONE);
            guider03.setVisibility(View.VISIBLE);
            guider04.setVisibility(View.GONE);
            guider05.setVisibility(View.GONE);

        }


    }


    @Override
    public void showLoadUserInfoFail(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void guideToRealName() {
        final RealNamePopView popView = new RealNamePopView(this);
        popView.setOnClickListener(new RealNamePopView.OnClickListener() {
            @Override
            public void onClickConfirm(View v) {
                IDCardAuthActivity.start(MerchantContainerActivity.this);
                popView.dismiss();
            }
        });

        popView.show();
    }

    @Override
    public void showUpdate(UpdateInfo updateInfo) {
        UpdatePopView popView = new UpdatePopView(this, updateInfo);
        popView.setOnClickImmediatelyGo(this);
        popView.show();
    }

    @Override
    public void navToLogin() {
        LoginActivity.start(this);
    }

    @Override
    public void showNotice(NoticeModel.NoticeBean noticeBean) {
        NoticePopView noticePopView = new NoticePopView(this, noticeBean);
        noticePopView.show();
    }

    @Override
    public void showoutline() {
        OutlinePopView outlinePopView = new OutlinePopView(this);
        outlinePopView.setOnClickListener(new OutlinePopView.OnClickListener() {
            @Override
            public void onClickConfirm(View v) {
                EquipmentCardSlotActivity.start(MerchantContainerActivity.this);
            }
        });
        outlinePopView.show();
    }

    public void shownetpopview() {
        netPopView = new NetPopView(this, this);
        netPopView.show();

    }

    @Override
    public void gotopartner() {
        WebActivity.startToH5(this, "toBePartner", 4);
    }


    @Override
    public void showDownCompleted(final String appFilePath) {
        if (downloadDialog != null) {
            downloadDialog.dismissDialog();
            downloadDialog = null;
        }
        mInstallUtil = new InstallUtil(this, appFilePath);
        mInstallUtil.install();
        //安装app
//        ApkUtil.openFile(new File(appFilePath), this);
    }

    @Override
    public void showDownProgress(int progress) {
        if (downloadDialog != null) {
            downloadDialog.setUpDateProgress(100, progress);
        }
    }

    @Override
    public void showDownloadFail() {
//        if (downloadDialog != null) {
//            downloadDialog.dismissDialog();
//        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onImmediatelyGo(String url) {
        downloadDialog = new DownloadDialog(this);
        downloadDialog.builder().setMsg("版本更新中...").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                updatePresenter.downloadAPK(ApkUtil.getAppSystemPath(App.app), url);
            }
        }).start();
    }

    @Override
    public void onClickItem() {
        int net = NetWorkUtils.getAPNType(this);
        if (net == 0) {
            Toast.makeText(this, "请连接网络！", Toast.LENGTH_LONG).show();


        } else {
            presenter.init();
            netPopView.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == InstallUtil.UNKNOWN_CODE) {
            mInstallUtil.install();//再次执行安装流程，包含权限判等
        }
    }
}